package com.itheima.web;

import com.itheima.Service.UserService;
import com.itheima.dao.pojo.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取浏览器传递的数据 用map集合的方式
        Map<String, String[]> parameterMap = request.getParameterMap();
        //擦混稿件用户对象
        User user1 = new User();
        //调用方法将集合封装到对象各中
        try {
            BeanUtils.populate(user1,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //Service创建对象调用添加用户的方法
        UserService userService = new UserService();
        boolean b = userService.addUser(user1);
        //判断返回值
        if (b){
            //如果b==true 表示插入成功 跳转到成功的页面
            request.getRequestDispatcher("add_ok.jsp").forward(request,response);
        }else {
            //表示没插入成功 跳转到添加失败的页面
            request.getRequestDispatcher("add_sb.jsp").forward(request,response);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
